<?php

namespace app\common\model;

use app\common\model\order\Order;
use app\common\model\user\Level;
use think\Model;

/**
 * 会员余额日志模型
 */
class MoneyLog extends Model
{

    // 表名
    protected $name = 'user_money_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
        'money_text',
        'createtime_text',
    ];


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    public function getTypeList()
    {
        return ['1' => __('收入'), '2' => __('支出')];
    }
    public function getMoneyTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['source_type']) ? $data['source_type'] : '');
        $list = $this->getMoneyType();
        return isset($list[$value]) ? $list[$value] : '';
    }
    const no_withdraw_change = [];
    const money_change = [
        500, // => '余额支付',
        501, //=> '余额提现申请',
        502, //=> '提现审核失败返回余额',
        503, //=> '订单直推收益',
        504, //=> '订单间推收益',
        505, //=> '升级PLUS直推收益',
        506, //=> '升级PLUS间推收益',
        507, //=> '分享用户收益',
        508, //=> '商家收益',
    ];
    const frozen_money_change = [];
    //返回变动字段
    public static function getChangeField($source_type)
    {

        $field = '';
        if (in_array($source_type, self::money_change)) {
            $field = 'money';
        }

        if (in_array($source_type, self::frozen_money_change)) {
            $field = 'frozen_money';
        }
        if (in_array($source_type, self::no_withdraw_change)) {
            $field = 'no_money';
        }
        return $field;
    }
    public static function getMoneyType()
    {
        return [
            500 => '余额支付',
            501 => '余额提现申请',
            502 => '提现审核失败返回余额',
            503 => '订单直推收益',
            504 => '订单间推收益',
            505 => '升级PLUS直推收益',
            506 => '升级PLUS间推收益',
            507 => '分享用户收益',
            508 => '商家收益',
        ];
    }
    /**
     * Notes:记录会员账户流水，如果变动类型是成长值，且是增加的，则调用更新会员等级方法。该方法应在添加用户账户后调用
     * @param int $user_id  用户id
     * @param float $amount 变动数量
     * @param int $change_type  变动类型：1-增加；2-减少
     * @param int $source_type 来源类型
     * @param string $source_id 来源id
     * @param string $source_sn 来源单号
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function income($user_id, $amount, $change_type, $source_type, $source_sn = '', $uid = 0)
    {
        $user = new User;
        $user = $user->get($user_id);

        if (empty($user)) {
            return false;
        }

        $field = self::getChangeField($source_type);
        $before = $user->$field;

        if ($change_type == 1) {
            $user->setInc($field, $amount);
        } else {
            $user->setDec($field, $amount);
            $amount = -$amount;
        }
        $left_amount = $user->$field;
        $list =  self::getMoneyType();
        $account_log = new self;
        $data['type'] = $change_type;
        $data['order_sn'] = $source_sn;
        $data['user_id'] = $user_id;
        $data['money'] = $amount ?? 0;
        $data['before'] = $before ?? 0;
        $data['after'] = $left_amount ?? 0;
        $data['memo'] = $memo ?? (isset($list[$source_type]) ? $list[$source_type] : '');
        $data['source_type'] = $source_type;
        $data['uid'] = $uid;
        $account_log->allowField(true)->save($data);
        return true;
    }


    //订单分佣
    public static function subcommission($uid, $order_sn)
    {
        $user = User::get($uid);
        $order = Order::get(['orderid' => $order_sn]);
        if ($order->order_status != '40') {
            return;
        }
        $total_fee = $order->total_fee;
        //分享分佣
        $share_earnings = floatval(config('site.share_earnings'));
        if ($share_earnings > 0 && $share_earnings <= 100 && $order->share_uid > 0) {
            $earnings_bl = bcdiv($share_earnings, 100, 2);
            $earnings = bcmul($order->goods_price,  $earnings_bl, 2);
            self::income($order->share_uid, $earnings, 1, 507, $order_sn, $uid);
            $total_fee -= $earnings;
        }
        $pUser = User::get($user->pid);
        if ($pUser) {
            //直推分佣
            $direct_revenue = floatval(config('site.direct_revenue'));
            if ($direct_revenue > 0 && $direct_revenue <= 100) {
                $direct_thrust = bcdiv($direct_revenue, 100, 2);
                $firstMoney = self::firstEarnings($user->pid, $order->total_fee, $direct_thrust, $order_sn, $uid);
                $total_fee -= $firstMoney;
            }
            //间推收益
            if ($pUser->pid) {
                $extrapolated_return = floatval(config('site.extrapolated_return'));
                if ($extrapolated_return > 0 && $extrapolated_return <= 100) {
                    $extrapolated = bcdiv($extrapolated_return, 100, 2);
                    $twoMoney =  self::twoEarnings($pUser->pid, $order->total_fee, $extrapolated, $order_sn, $uid);
                    $total_fee -= $twoMoney;
                }
            }
        }
        //商家收益
        if ($total_fee > 0) {
            self::income($order->shop_id, $total_fee, 1, 508, $order_sn, $uid);
        }
    }

    static function firstEarnings($user_id, $total_fee, $direct_thrust, $order_sn, $uid)
    {
        $money = bcmul($total_fee,  $direct_thrust, 2);
        if ($money <= 0) {
            return;
        }
        $pUser = User::get($user_id);
        if (!$pUser) {
            return;
        }
        self::income($user_id, $money, 1, 503, $order_sn, $uid);
        return $money;
    }
    static function twoEarnings($user_id, $total_fee, $extrapolated, $order_sn, $uid)
    {
        $twomoney = bcmul($total_fee,  $extrapolated, 2);
        if ($twomoney <= 0) {
            return;
        }
        self::income($user_id, $twomoney, 1, 504, $order_sn, $uid);
        return $twomoney;
    }
    //购买VIP分佣
    public static function vipcommission($uid, $order_sn)
    {
        $user = User::get($uid);
        $order = Level::get(['orderid' => $order_sn]);
        if ($user->pid <= 0) {
            return;
        }
        //直推分佣
        $direct_revenue = floatval(config('site.direct_revenue'));
        if ($direct_revenue <= 0 || $direct_revenue > 100) {
            return;
        }
        $direct_thrust = bcdiv($direct_revenue, 100, 2);
        if ($direct_thrust <= 0) {
            return;
        }
        $money = bcmul($order->payamount,  $direct_thrust, 2);
        if ($money <= 0) {
            return;
        }
        $pUser = User::get($user->pid);
        if (!$pUser) {
            return;
        }
        self::income($user->pid, $money, 1, 505, $order_sn, $uid);
        //间推收益
        if ($pUser->pid <= 0) {
            return;
        }
        $extrapolated_return = floatval(config('site.extrapolated_return'));
        if ($extrapolated_return <= 0 || $extrapolated_return > 100) {
            return;
        }
        $extrapolated = bcdiv($extrapolated_return, 100, 2);
        if ($extrapolated <= 0) {
            return;
        }
        $twomoney = bcmul($order->payamount,  $extrapolated, 2);
        if ($twomoney <= 0) {
            return;
        }
        self::income($pUser->pid, $twomoney, 1, 506, $order_sn, $uid);
    }
}
